<template>
  <div>
    <el-form
      ref="lmform"
      label-width="100px"
      :model="form"
      :rules="rules"
      status-icon
    >
      <el-form-item label="角色名" prop="name">
        <el-input
          v-model="form.name"
          placeholder="请输入角色名"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain @click="save()">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  name: "RoleEdit",
  props: {
      dialogshow: {
          type: Boolean
      },
      editId: {
        type: Number,
        default: null
      }
  },
  data() {
    const checkdata = (rule,value,callback) => {
      const params = {value: value};
      if(this.editId) {
        params.id = this.editId
      }
      this.$axios.get('/ums-role/check',params,response => {
        if(response.obj > 0) {
            callback(new Error('数据已经存在，请重新输入'))
        } else {
            callback()
        }
      })
    }
    return {
      form: {
        name: "",
      },
      rules: {
        name: [
          { required: true, message: "角色名不能为空", trigger: "blur" },
          { min: 1, max: 20, message: "角色名长度小于20", trigger: "blur" },
          { validator: checkdata,  trigger: 'blur' }
        ]
      },
      url: '/ums-role/add'
    };
  },
  created() {
    if(this.editId) {
      this.url = '/ums-role/update'
      this.getById()
    }
  },
  methods: {
    save() {
      this.$axios.post(this.url, this.form, () => {
        this.$emit('update:dialogshow',false)
        this.$emit('getTable')
      },this.$refs['lmform'])
    },
    getById() {
      this.$axios.get('/ums-role/getone',{id: this.editId}, response => {
        for(let key in this.form) {
          this.form[key] = response.obj[key]
        }
        this.form.id = response.obj.id
      })
    }
  },
};
</script>
<style lang="less" scoped>
</style>